package com.gavin.plugin.database.optimize;

import com.gavin.model.Model;
import com.gavin.model.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @title 占位符替换
 * @author Yudao 王冬明（woyuwodao@gmail.com）
 * @version 1.0
 * @date 2018/12/2 下午8:43
 * @package com.renrenhui.center.user.rpc.util
 */
public class SqlParse {
    private static final Logger logger = LoggerFactory.getLogger(SqlParse.class);
    /**
     * Prefix for system property placeholders: "{"
     */
    public static final String DEFAULT_PLACEHOLDER_PREFIX = "{";
    /**
     * Suffix for system property placeholders: "}"
     */
    public static final String DEFAULT_PLACEHOLDER_SUFFIX = "}";

    public static final boolean NULL2STRING=false;//默认是null值


    public static String parse(String openToken, String closeToken, String text, Model params) {
        if (params == null || params.empty()) {
            return text;
        }
//        int argsIndex = 0;
        if (text == null || text.isEmpty()) {
            return "";
        }
        char[] src = text.toCharArray();
        int offset = 0;
        // search open token
        int start = text.indexOf(openToken, offset);
        if (start == -1) {
            return text;
        }
        final StringBuilder builder = new StringBuilder();
        StringBuilder expression = null;
        while (start > -1) {
            if (start > 0 && src[start - 1] == '\\') {
                // this open token is escaped. remove the backslash and continue.
                builder.append(src, offset, start - offset - 1).append(openToken);
                offset = start + openToken.length();
            } else {
                // found open token. let's search close token.
                if (expression == null) {
                    expression = new StringBuilder();
                } else {
                    expression.setLength(0);
                }
                builder.append(src, offset, start - offset);
                offset = start + openToken.length();
                int end = text.indexOf(closeToken, offset);
                while (end > -1) {
                    if (end > offset && src[end - 1] == '\\') {
                        // this close token is escaped. remove the backslash and continue.
                        expression.append(src, offset, end - offset - 1).append(closeToken);
                        offset = end + closeToken.length();
                        end = text.indexOf(closeToken, offset);
                    } else {
                        expression.append(src, offset, end - offset);
                        offset = end + closeToken.length();
                        break;
                    }
                }
                if (end == -1) {
                    // close token was not found.
                    builder.append(src, start, src.length - start); offset = src.length;
                } else {
                    builder.append(value(expression,params));
                    offset = end + closeToken.length();
//                    argsIndex++;
                }
            }
            start = text.indexOf(openToken, offset);
        }
        if (offset < src.length) {
            builder.append(src, offset, src.length - offset);
        }
        return builder.toString();
    }


    public static String defaultParse(String text, Model params) {
        return parse(DEFAULT_PLACEHOLDER_PREFIX, DEFAULT_PLACEHOLDER_SUFFIX, text, params);
    }

    private static String value(StringBuilder expression,Model params){
        int tiIndex=expression.indexOf("TI:");
        int aiIndex=expression.indexOf("ai:");
        int spIndex=expression.indexOf("|");



        String value=null;
        if(params==null || params.empty()){
            return value;
        }else{
            String defaultValue=null;
            if(expression.indexOf("|")!=-1){//包含默认值
                String[] temps=expression.toString().split("\\|");
                defaultValue=temps[1];
                expression.setLength(0);
                expression=expression.append(temps[0]);
            }
            value = params.get(expression.toString())==null?defaultValue:String.valueOf(params.get(expression.toString()));

        }

        return value;
    }

    public static void main(String[] args) {
        long startTime=System.currentTimeMillis();
        for (int i = 0; i < 1; i++) {
            String text= "delete from {TI:tbTemplatesRecord, strUserName} where strUserName={strUserName}"+i;
            Model model=Request.build().set("num","惊呆了撒娇了").set("strUserName","小明").model();
            System.out.println(defaultParse(text,model));
        }
        System.out.println("耗时："+(System.currentTimeMillis()-startTime));
    }
}
